package bar.dark.lee.alarm.add;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import bar.dark.lee.alarm.R;
import bar.dark.lee.alarm.SuperActivity;
import bar.dark.lee.alarm.add.date.DateListActivity;
import bar.dark.lee.alarm.beginalarm.BDAlarmManager;
import bar.dark.lee.alarm.beginalarm.BDAlarmService;
import bar.dark.lee.alarm.common.BDUtil;
import bar.dark.lee.alarm.common.CustomTimePickerDialog;
import bar.dark.lee.alarm.effect.EffectListActivity;
import bar.dark.lee.alarm.query.AlarmData;
import bar.dark.lee.alarm.sound.SoundActivity;
import bar.dark.lee.alarm.sound.SoundData;

/**
 * 알람을 추가하거나 수정하는 화면
 * @author HyoJun Lee
 *
 */
public class AddActivity extends SuperActivity 
{
	public static final int REQUEST_EFFECT = 0;
	public static final int REQUEST_SOUND = 1;
	public static final int REQUEST_DATE = 2;
	public static final int REQUEST_TIME = 3;
	public static final int REQUEST_SNOOZE = 4;
	public static final int REQUEST_MEMO = 5;
	
	private View viewEffect;
	private TextView textEffect;
	private View viewSound;
	private View viewDate;
	private TextView textDate;
	private View viewSnooze;
	private TextView textSnooze;
	private View viewTime;
	private TextView textTime;
	private View viewMemo;
	private TextView textMemo;
	
	private TextView soundTextView;
	
	private Intent getIntent;
	private int addFlag;
	
	private Button saveButton;
	
	private String timeHourSelect;
	private String timeMinSelect;
	private String snoozeHourSelect;
	private String snoozeMinSelect;
	
	private CustomTimePickerDialog builder;
	
	private ArrayList<Integer> listEffect;
	
	private String effect;
	private String dateType;
	
	private SoundData soundData;
	
	private ArrayList<String> listDate;
	private ArrayList<String> listDateSelect;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.add_activity);
		
		setTitle(getString(R.string.add_title));
		
		setFindView();
		setClickListener();
		setDataSetting();
	}
	
	@Override
	protected void tipButton() {
		
	}
	
	@Override
	public void setFindView() {
		viewEffect = findViewById(R.id.addEffect);
		textEffect = (TextView) findViewById(R.id.addEffectTextView);
		viewSound = findViewById(R.id.addSound);
		viewDate = findViewById(R.id.addDate);
		textDate = (TextView) findViewById(R.id.addDateTextView);
		viewTime = findViewById(R.id.addTime);
		textTime = (TextView) findViewById(R.id.addTimeTextView);
		viewSnooze = findViewById(R.id.addSnooze);
		textSnooze = (TextView) findViewById(R.id.addSnoozeTextView);
		viewMemo = findViewById(R.id.addMemo);
		
		soundTextView = (TextView) findViewById(R.id.addSoundTextView);
		textMemo = (TextView) findViewById(R.id.addMemoTextView);
		
		saveButton = (Button) findViewById(R.id.addbtnSave);
	}
	
	@Override
	public void setDataSetting() {
		
		// 효과 설정
		listEffect = new ArrayList<Integer>();
		textEffect.setText(setEffectTextView());
		
		// 요일 설정
		listDate = new ArrayList<String>();
		listDateSelect = new ArrayList<String>();
		listDate.add(gets(R.string.datelist_sunday));
		listDate.add(gets(R.string.datelist_monday));
		listDate.add(gets(R.string.datelist_tuesday));
		listDate.add(gets(R.string.datelist_wednesday));
		listDate.add(gets(R.string.datelist_thursday));
		listDate.add(gets(R.string.datelist_friday));
		listDate.add(gets(R.string.datelist_saturday));
		textDate.setText(gets(R.string.datelist_justone));
		dateType = "";
		
		// 시간 설정
		Calendar c = Calendar.getInstance();
		timeHourSelect = c.get(Calendar.HOUR_OF_DAY)+"";
		timeMinSelect = c.get(Calendar.MINUTE)+"";
		textTime.setText(BDUtil.getTwoNumber(Integer.parseInt(timeHourSelect)) + gets(R.string.add_hour) 
				+ " " + BDUtil.getTwoNumber(Integer.parseInt(timeMinSelect)) + gets(R.string.add_min)
				+ gets(R.string.add_e));
		
		// 다시알림 설정
		snoozeHourSelect = "00";
		snoozeMinSelect = "00";
		textSnooze.setText(gets(R.string.add_justone));
		
		// 메모 설정
		textMemo.setText(gets(R.string.add_no_memo) + " " + gets(R.string.add_ringring));
		
		ArrayList<SoundData> list = query.getAlarmSound(superContext);
		
		soundData = list.get(0);
		
		soundTextView.setText(soundData.getFileName());
	}
	
	@Override
	public void setClickListener() {
		
		viewEffect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(superContext, EffectListActivity.class);
				intent.putIntegerArrayListExtra(EffectListActivity.EFFECT_SELECT, listEffect);
				startActivityForResult(intent, REQUEST_EFFECT);
			}
		});
		
		viewSound.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(superContext, SoundActivity.class);
				intent.putExtra(SoundActivity.SELECT_DATA, soundTextView.getText().toString());
				startActivityForResult(intent, REQUEST_SOUND);
			}
		});
		
		viewDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(superContext, DateListActivity.class);
				intent.putExtra(DateListActivity.CHECKDATA, listDate);
				intent.putExtra(DateListActivity.CHECKSELECT, listDateSelect);
				startActivityForResult(intent, REQUEST_DATE);
			}
		});
		
		
		viewTime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder = new CustomTimePickerDialog(superContext, 2, Integer.parseInt(timeHourSelect), Integer.parseInt(timeMinSelect));
				builder.setPositiveButton(R.string.customTimePickerDialog_ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						timeHourSelect = builder.getHour();
						timeMinSelect = builder.getMin();
						textTime.setText(BDUtil.getTwoNumber(Integer.parseInt(timeHourSelect)) + gets(R.string.add_hour) 
								+ " " + BDUtil.getTwoNumber(Integer.parseInt(timeMinSelect)) + gets(R.string.add_min)
								+ gets(R.string.add_e));
					}
				});
				builder.setNegativeButton(R.string.customTimePickerDialog_cancel, null);
				
				builder.show();
			}
		});
		
		viewSnooze.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder = new CustomTimePickerDialog(superContext, 2, Integer.parseInt(snoozeHourSelect), Integer.parseInt(snoozeMinSelect));
				builder.setPositiveButton(R.string.customTimePickerDialog_ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						snoozeHourSelect = builder.getHour();
						snoozeMinSelect = builder.getMin();
						
						if (snoozeHourSelect.equals("0"))
						{
							if (snoozeMinSelect.equals("0"))
							{
								textSnooze.setText(gets(R.string.add_justone));
							}
							else
							{
								textSnooze.setText(BDUtil.getTwoNumber(Integer.parseInt(snoozeMinSelect)) + gets(R.string.add_min)
									+ " " + gets(R.string.add_term));
							}
						}
						else
						{
							textSnooze.setText(BDUtil.getTwoNumber(Integer.parseInt(snoozeHourSelect)) + gets(R.string.add_hours) 
									+ " " + BDUtil.getTwoNumber(Integer.parseInt(snoozeMinSelect)) + gets(R.string.add_min)
									+ " " + gets(R.string.add_term));
						}
					}
				});

				builder.setNeutralButton(R.string.customTimePickerDialog_init, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						snoozeHourSelect = "0";
						snoozeMinSelect = "0";
						textSnooze.setText(gets(R.string.add_justone));
					}
				});
				builder.setNegativeButton(R.string.customTimePickerDialog_cancel, null);
				
				builder.show();
			}
		});
		
		viewMemo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_SOUND)
		{
			if (resultCode == RESULT_OK)
			{	
				soundData = null;
				
				soundData = data.getParcelableExtra(SoundActivity.SOUND_FILE_DATA);
				
				soundTextView.setText(soundData.getFileName());
			}
		}
		else if (requestCode == REQUEST_DATE)
		{
			if (resultCode == RESULT_OK)
			{
				String selectStr = "";
				dateType = "";
				
				listDateSelect.clear();
				
				int [] arrayDateSelect = data.getIntArrayExtra(DateListActivity.CHECKSELECT);
				
				for (int i=0; i<arrayDateSelect.length; i++)
				{
					if (arrayDateSelect[i] == 1)
					{
						selectStr += listDate.get(i) + ", ";
						listDateSelect.add(i+"");
						dateType += i + ",";
					}
				}
				
				if (selectStr.length() > 0)
				{
					selectStr = selectStr.trim().substring(0, selectStr.lastIndexOf(","));
					textDate.setText(selectStr + gets(R.string.datelist_day));
					
					dateType = dateType.trim().substring(0, dateType.lastIndexOf(","));
				}
				
				if (listDateSelect.size() == listDate.size())
				{
					selectStr = gets(R.string.datelist_always);
					textDate.setText(selectStr);
					
					dateType = dateType.trim().substring(0, dateType.lastIndexOf(","));
				}
				else if (listDateSelect.size() == 0)
				{
					selectStr = gets(R.string.datelist_justone);
					textDate.setText(selectStr);
					
					dateType = "";
				}
			}
		}
		else if (requestCode == REQUEST_EFFECT)
		{
			if (resultCode == RESULT_OK)
			{
				listEffect = data.getIntegerArrayListExtra(EffectListActivity.EFFECT_SELECT);
				textEffect.setText(setEffectTextView());
			}
		}
	}
	
	private String setEffectTextView()
	{
		String strEffect = "";
		effect = "";
		
		for (int i=0; i<listEffect.size(); i++)
		{
			switch (listEffect.get(i)) 
			{
				case EffectListActivity.EFFECT0:
					strEffect += gets(R.string.effectlist_0_title) + ", ";
					effect += EffectListActivity.EFFECT0 + ",";
					break;
				case EffectListActivity.EFFECT1:
					strEffect += gets(R.string.effectlist_1_title) + ", ";
					effect += EffectListActivity.EFFECT1 + ",";
					break;
				case EffectListActivity.EFFECT2:
					strEffect += gets(R.string.effectlist_2_title) + ", ";
					effect += EffectListActivity.EFFECT2 + ",";
					break;
				case EffectListActivity.EFFECT3:
					strEffect += gets(R.string.effectlist_3_title) + ", ";
					effect += EffectListActivity.EFFECT3 + ",";
					break;
				case EffectListActivity.EFFECT4:
					strEffect += gets(R.string.effectlist_4_title) + ", ";
					effect += EffectListActivity.EFFECT4 + ",";
					break;
				case EffectListActivity.EFFECT5:
					strEffect += gets(R.string.effectlist_5_title) + ", ";
					effect += EffectListActivity.EFFECT5 + ",";
					break;
				default:
					break;
			}
		}
		
		if (strEffect.length() < 1)
		{
			strEffect = gets(R.string.effectlist_no_effect);
			effect = "-1";
		}
		else
		{
			strEffect = strEffect.trim().substring(0, strEffect.lastIndexOf(","));
			effect = effect.trim().substring(0, effect.lastIndexOf(","));
		}
				
		return strEffect;
	}
	
	private void setInsertData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("time", timeHourSelect + "," + timeMinSelect + "");
		map.put("timename", timeHourSelect + " : " + timeMinSelect);
		map.put("effect", effect);
		map.put("effectname", textEffect.getText().toString());
		map.put("sound", soundData.getFileLocation());
		map.put("soundname", soundData.getFileName());
		map.put("date", dateType);
		map.put("datename", textDate.getText().toString());
		map.put("snoozeminute", snoozeHourSelect + snoozeMinSelect + "");
		map.put("snoozeminutename", textSnooze.getText().toString());
		map.put("memo", textMemo.getText().toString());
		
		if (sql.insert(superContext, map, "alarm") == 0)
		{
			int id = query.getAlarmDataMax(superContext);
			
			Intent intent = new Intent(superContext, BDAlarmService.class);
			intent.putExtra(BDAlarmManager.ALERM_FLAG_POS, effect);
			
			BDAlarmManager am = new BDAlarmManager(superContext);
			am.setStartAlarm(id, intent, 
					timeHourSelect + "," + timeMinSelect + "");
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0)
			{
				if (arg0[1] == 0)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setInsertData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -2;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -2;
						}
					}
					
					return 0;
				}
			}
			else
			{
				return arg0[0];
			}
			
			return -1;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -2)
			{
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0)
			{
				BDUtil.showDialogFinish(superContext, "알림", "알람이 저장되었습니다.");
			}
		}
	}
}
